package com.da.core.context.impl;

import com.da.core.app.BaseApp;
import com.da.core.app.impl.BIOApp;
import com.da.core.context.Request;
import com.da.core.context.Response;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @author da
 * @time 2023/9/17 上午 7:18
 */
public class BIOContext extends BaseContext {
    //    当前上下文的通道
    private final Socket socket;
    private final BaseApp app;

    public BIOContext(Socket socket, BaseApp app) {
        this.socket = socket;
        this.app = app;
        this.request = new Request(this);
        this.response = new Response(this);
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            // 读取客户端发送的HTTP请求
            request.resolveRequest(reader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public BaseApp getApp() {
        return this.app;
    }

    @Override
    public InputStream getInputStream() {
        try {
            return this.socket.getInputStream();
        } catch (IOException e) {
            return null;
        }
    }

    @Override
    public void flashDataToResponse() {
        String response = buildResponseMsg();
        try {
//            获取写入对象
            OutputStream writer = this.socket.getOutputStream();
//            写入响应头数据
            writer.write(response.getBytes(StandardCharsets.UTF_8));
//            处理data数据
            if (null != this.getData() && this.getData().length > 0) {
                writer.write(this.getData());
            } else {
                writer.write("<h1 style='color:red;'>没有数据响应(这是框架的默认响应)</h1>".getBytes(StandardCharsets.UTF_8));
            }
            writer.flush();
        } catch (IOException e) {
            this.setException(e);
        }
    }

    @Override
    public void close() {
        if (null != this.socket) {
            try {
                this.socket.close();
            } catch (IOException e) {
                this.setException(e);
            }
        }
    }
}
